package cn.xiuxius.embedded.dependencyscan;

import cn.xiuxius.embedded.keil.KeilProjectXML;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.nio.file.Path;

@Getter
@Setter
@Accessors(chain = true)
@ToString
public class KeilFile {
    private String name;
    private String group;
    private String path;
    private String absolutePath;
    private FileType type;

    public KeilProjectXML.KeilFile toKeilFile() {
        String path = Path.of(this.path).normalize().toString();
        //path转成本地路径
        return new KeilProjectXML.KeilFile()
                .setName(this.name)
                //path转成本地路径
                .setPath(safeAddRelativePrefix(path))
                .setGroup(this.group)
                .setType(this.type);
    }


    public static String safeAddRelativePrefix(String inputPath) {
        Path p = Path.of(inputPath).normalize();

        if (p.isAbsolute()) {
            // 绝对路径，直接返回字符串形式
            return p.toString();
        }

        // 不是绝对路径，检查第一个路径元素
        if (p.getNameCount() > 0) {
            String firstName = p.getName(0).toString();
            if (firstName.equals(".") || firstName.equals("..")) {
                // 已经是相对路径，且带了相对前缀，直接返回
                return p.toString();
            }
        } else {
            // 可能是空路径，直接返回 "."
            return ".";
        }
        // 否则给路径前加上 "." 前缀，变成 "./xxx" 或 ".\xxx"
        Path result = Path.of(".").resolve(p);
        return result.toString();
    }

}
